package com.chooseCourses.servlet.teacher;

import com.chooseCourses.dao.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/TeacherModified")
public class TeacherModified extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Served at: ").append(req.getContextPath());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = URLEncoder.encode(req.getParameter("userName"),"UTF-8");//给中文编码为UTF-8
        String userId = req.getParameter("userId");
        String oldPw = req.getParameter("oldPw");
        String newPw = req.getParameter("newPw");

        //创建db对象
        BaseDao baseDao = new BaseDao();
        //创建一个判断该老师输入的旧密码是否一致的sql
        String sql = "select * from teacher where id='" + userId + "' and loginpassword='" + oldPw + "'";
        //创建更新sql语句
        String updateSql = "update teacher set loginpassword=? where id=?";

        //创建一个rs结果集,ps对象
        PreparedStatement ps;
        ResultSet rs;
        //调用db中的查询方法
        try {
            ps = baseDao.getConnection().prepareStatement(sql);
            rs = ps.executeQuery();//执行语句
            //判断旧密码是否存在,rs.next()返回的是布尔值
            if(rs.next()) {//存在,则执行更新操作
                //调用更新操作
                ps = baseDao.getConnection().prepareStatement(updateSql);
                //要更新的数据
                ps.setString(1, newPw);
                ps.setString(2, userId);
                ps.executeUpdate();//执行更新
                //成功返回管理员信息页面,这里可以设置一个提示页面再跳,不设置也可以
                req.getRequestDispatcher("teacher/teacherMes.jsp?userName=" + userName + "&userId=" + userId).forward(req,resp);
            }else {//不存在,则跳回修改页面,并提示错误
                req.setAttribute("message","旧密码不正确，无法设置密码，请重新输入");
                req.getRequestDispatcher("teacher/TeacherModified.jsp?userName=" + userName + "&userId=" + userId).forward(req,resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        doGet(req, resp);
    }

    public TeacherModified() {
        super();
    }
}
